import shlex
import datetime
import subprocess
import time

def executeCommand(cmd,cwd=None,timeout=None,shell=False):
    if shell:
        cmdStringList = cmd
    else:
        cmdStringList = shlex.split(cmd)

    endTime = 0;
    if timeout:
        endTime = datetime.datetime.now() + datetime.timedelta(seconds=timeout)
    
    sub = subprocess.Popen(cmdStringList,cwd=cwd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=shell,bufsize=4096)

    while sub.poll() is None:
        time.sleep(0.1)
        if timeout:
            if endTime <= datetime.datetime.now():
                raise Exception('Timeout: {}'.format(cmd))
    return sub.stdout.read()

if __name__ == "__main__":
    print(executeCommand("ls"))